package model

import (
	"errors"

	"github.com/google/uuid"
	"github.com/jinzhu/gorm"
)

// ConfigInfo Config structure
type ConfigInfo struct {
	gorm.Model
	AlgorithmName string    `json:"algorithmname"`
	ConfigParams  string    `json:"configparams"`
	Port          int64     `json:"port"`
	CameraList    string    `json:"cameralist"`
	CameraID      int64     `json:"camera_id"`
	UUID          uuid.UUID `json:"uuid"`
	// 置信度阈值
	ConfidenceThreshold int64 `json:"confidence_threshold"`

	// 处理帧率
	ProcessingFrameRate int64 `json:"processing_frame_rate"`

	// 报警小视频时长
	AlarmVideoTime int64 `json:"alarm_video_time"`

	// 安全通道检测 规则区域配置，视频监控画面上配置4个点，4个点构成凸四边形
	RegularAreaCoordinates string `json:"Regular_area_coordinates"`

	// 安全员颜色 用于告知算法穿戴哪种颜色工服或安全帽的安全员进入不能报警，默认全部报警
	SecurityOfficerColor string `json:"security_officer_color"`

	FrameNumberForAlarm int64 `json:"frame_number_for_alarm"`
}

// AddNewConfig add a new Config
func AddNewConfig(configInfo ConfigInfo) error {

	GenUUID, err := uuid.NewUUID()
	configInfo.UUID = GenUUID
	if err != nil {
		return err
	}

	db.Save(&configInfo)

	return nil

}

// GetConfigWithAlgorithmName get a single Config
func GetConfigWithAlgorithmName(algorithmName string) ([]ConfigInfo, error) {
	var Config []ConfigInfo

	db.Where("algorithm_name = ?", algorithmName).Find(&Config)

	if len(Config) == 0 {
		err := errors.New("no Config found")
		return []ConfigInfo{}, err
	}

	return Config, nil
}

// ExistConfigByID check the id is exist or not
func ExistConfigByID(ID int) bool {
	var myConfig ConfigInfo
	db.Select("id").Where("id = ?", ID).First(&myConfig)
	if myConfig.ID > 0 {
		return true
	}
	return false
}

// UpdateConfig edit Config info
func UpdateConfig(id int, data interface{}) bool {
	db.Model(&ConfigInfo{}).Where("id = ?", id).Updates(data)

	return true
}

// DeleteConfig delete the config info from db
func DeleteConfig(id int) bool {
	db.Where("id = ?", id).Delete(&ConfigInfo{})

	return true
}

// GetAllConfigs get the all Configs info from db
func GetAllConfigs() (result []ConfigInfo, err error) {
	var myConfig []ConfigInfo
	db.Find(&myConfig)

	if len(myConfig) == 0 {
		err = errors.New("no Config found")
		return nil, err
	}
	return myConfig, nil
}
